<!--
 * @description  : 实地核查方位图-实地核查地图页面
 * @create       : 2024-7-30
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"> </theme-navbar>
    <!-- #endif -->
    <view class="m-content">
      <view :style="{ width: getContainerWidth(), height: getContainerHeight() }" id="container"></view>
      <view class="m-market">
        <view class="add-entity" @click="showAddTypePicker = true">
          <u-image width="26px" src="/static/market/add.png" mode="widthFix"></u-image>
          <view class="add-text">新增点位</view>
        </view>
        <view class="entity-list">
          <u-swipe-action
            v-for="(item, index) in entityList"
            :key="item.id"
            :index="index"
            :show="item.show"
            :options="swipeOptions"
            root-class="swipe-root"
            @open="handleOpenSwipe"
            @click="handleEntityDelete(item)"
          >
            <u-checkbox shape="circle" v-model="item.checked" :name="item.id" @change="checkboxChange">
              <view class="title-wrap">
                <view class="left">
                  <view class="name">{{ item.name }}</view>
                  <view class="address">{{ item.address }}</view>
                </view>
                <view class="right">
                  <u-image :width="item.entityType === 'school' ? '42px' : '30px'" :style="getImageStyle(item.entityType)" :src="getEntitySrc(item.entityType)" mode="widthFix"></u-image>
                  <view class="distance" :style="getDistanceStyle(item.entityType)">直线距离
                    <view class="number">{{ item.lineDistance }}</view>米</view>
                </view>
              </view>
            </u-checkbox>
          </u-swipe-action>
        </view>
        <u-button class="button" type="primary" @click="handleNextStep">
          确定位置信息，下一步
        </u-button>
      </view>
      <u-select v-model="showAddTypePicker" mode="single-column" :list="addEntityTypeList" @confirm="addEntityTypeConfirm"></u-select>
    </view>
  </view>
</template>

<script>
import { AMapMixin } from "@/common/AMapMixin.js";
import certificateService from "@/service/certificate/certificate.service.js";

const addEntityTypeList = [
  {
    label: "零售户",
    value: "retailer"
  },
  {
    label: "学校",
    value: "school"
  },
  {
    label: "自定义描点",
    value: "custom"
  }
];

const dataTypeMap = {
  "01": { label: "零售户", value: "retailer" },
  "02": { label: "幼儿园", value: "kindergarten" },
  "03": { label: "中小学", value: "school" }
};
export default {
  onLoad(opt) {
    this.curCords = new AMap.LngLat(opt.longitude, opt.latitude);
  },
  onShow() {
    uni.$on("addEntity", data => {
      uni.$off("addEntity");
      const incrList = JSON.parse(data.list).map(item => {
        return {
          ...item,
          show: false,
          checked: false
        };
      });
      // 获取dom节点
      setTimeout(() => {
        const ids = this.entityList.map(item => item.id);
        const list = incrList.filter(item => !ids.includes(item.id));
        if (!list.length) return;
        this.entityList.push(...list);
        this.drawEntityInstance();
      }, 100);
    });
  },
  mixins: [AMapMixin],
  data() {
    return {
      curCords: null,
      checkboxValue: [],
      entityList: [],
      swipeOptions: [
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d"
          }
        }
      ],
      showAddTypePicker: false,
      // 新增实例类型列表
      addEntityTypeList,
      // 当前地图上Marker实例集合
      curMarkerList: []
    };
  },
  computed: {
    getEntitySrc() {
      return type => {
        return `/static/certificate/${type}_icon.svg`;
      };
    },
    getDistanceStyle() {
      return type => {
        return { bottom: type === "school" ? "-5rpx" : "-10rpx" };
      };
    },
    getImageStyle() {
      return type => {
        return {
          marginTop: type === "school" ? "-26rpx" : "-12rpx"
        };
      };
    },
    // 底部数据栏高度
    bottomHeight() {
      const len = this.entityList.length;
      return len < 3 ? len * 74 + 44 : 270;
    }
  },
  methods: {
    initAmap() {
      this.setMapInstance();
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.bottomHeight - this.$u.sys().statusBarHeight + "px";
      // #ifdef H5-DINGDING || H5-WECHAT
      p = this.$u.sys().windowHeight - this.bottomHeight - this.$u.sys().statusBarHeight + "px";
      // #endif
      return p;
    },
    async initEntityData() {
      const params = {
        longitude: this.curCords.getLng(),
        latitude: this.curCords.getLat(),
        areaCode: this.$storage.get("curConfirmInfo").curAreaCode,
        standardDistance: 200
      };
      this.$u.loading("加载中...");
      const res = await certificateService.getPeripheryInfos(params);
      this.$u.hideLoading();
      if (res.code == 200) {
        const list = res.data.map(item => {
          const { name, address, type, lng, lat, bizUUid, licNo } = item;
          return {
            name,
            address,
            type,
            bizUUid,
            licNo,
            longitude: lng,
            latitude: lat,
            id: bizUUid,
            entityType: dataTypeMap[type].value,
            show: false
          };
        });
        this.entityList = list;
      } else {
        this.$u.toast("请求失败:" + res.message);
      }
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + "px";
    },
    async setMapInstance() {
      if (!this.hasInited) return;
      this.amap = new AMap.Map("container", {
        center: this.curCords,
        showControlButton: true,
        zoom: 17
      });
      const _this = this;
      this.loadPlugin("AMap.ControlBar", function() {
        const controlBar = new AMap.ControlBar({
          position: {
            top: "10px",
            right: "10px"
          }
        });
        _this.amap.addControl(controlBar);
      });
      this.drawDefaultInstance();
      await this.initEntityData();
      this.drawEntityInstance();
    },
    // 绘制地图上的默认实例 当前位置 & 区域
    drawDefaultInstance() {
      const curLocation = new AMap.Marker({
        title: "当前位置",
        icon: new AMap.Icon({
          size: new AMap.Size(20, 30),
          imageSize: new AMap.Size(20, 30),
          image: "static/market/new-location.png" // 大图地址
        }),
        position: this.curCords
      });
      curLocation.setMap(this.amap);
      let circle = new AMap.Circle({
        center: this.curCords,
        radius: 200, //半径
        borderWeight: 3,
        strokeColor: "#89C3EF",
        strokeOpacity: 1,
        strokeWeight: 1,
        strokeOpacity: 1,
        strokeStyle: "solid",
        fillOpacity: 0.3,
        fillColor: "#C2D0DF",
        zIndex: 99,
        bubble: true
      });
      this.amap.add(circle);
    },
    // 绘制零售户 | 学校
    drawEntityInstance() {
      // 绘制前先清除已绘制实例
      this.clearMarker();
      if (!this.entityList.length) {
        return;
      }
      this.getDistanceAndSort();
      this.entityList.forEach(item => {
        this.drawMarker(item);
      });
    },
    // 测距 直线距离
    async getDistanceAndSort() {
      const distances = this.entityList.map(item => Math.round(this.curCords.distance(new AMap.LngLat(item.longitude, item.latitude))));
      // 维护距离字段 排序
      this.entityList = this.entityList
        .map((item, i) => {
          return {
            ...item,
            lineDistance: distances[i]
          };
        })
        .sort((a, b) => a.lineDistance - b.lineDistance);
    },
    drawMarker(opt) {
      const { entityType, name, checked } = opt;
      const active = checked ? "_active" : "";
      const sizes = entityType === "school" ? [40, 50] : [30, 40];
      const option = {
        title: name,
        icon: new AMap.Icon({
          image: `static/certificate/${entityType}_icon${active}.svg`,
          size: new AMap.Size(sizes[0], sizes[1]),
          imageSize: new AMap.Size(sizes[0], sizes[1])
        }),
        position: [opt.longitude, opt.latitude],
        extData: { id: opt.id, entityType: opt.entityType }
      };
      const marker = new AMap.Marker(option);
      marker.setMap(this.amap);
      this.curMarkerList.push(marker);
    },
    // 传marker实例则单清，否则全清
    clearMarker(instance) {
      if (instance) {
        instance.setMap(null);
        const idx = this.curMarkerList.findIndex(item => item.getExtData().id === instance.getExtData().id);
        this.curMarkerList.splice(idx, 1);
      } else {
        this.curMarkerList.forEach(item => {
          item.setMap(null);
        });
        this.curMarkerList = [];
      }
    },
    handleNextStep() {
      const checkedEntityList = this.entityList.filter(item => item.checked);
      const countMap = {
        retailer: 0,
        school: 0,
        kindergarten: 0
      };
      checkedEntityList.forEach(item => {
        countMap[item.entityType]++;
      });
      const content = `系统检测50米内有${countMap["retailer"]}个零售户、${countMap["school"]}个中小学、${countMap["kindergarten"]}个幼儿园`;
      const _this = this;
      uni.showModal({
        title: "提示",
        confirmText: "是",
        cancelText: "否",
        content,
        success: function(res) {
          if (!res.confirm) return;
          _this.$storage.set("checkedEntityList", checkedEntityList);
          _this.$u.route({
            url: "pages/certificate/fieldAudit/orientationDiagram/addLocation",
            params: {
              curLocation: _this.curCords
            }
          });
        }
      });
    },
    // 根据id查找marker实例
    findMarkerById(id) {
      let marker = null;
      for (let item of this.curMarkerList) {
        if (item.getExtData().id === id) {
          marker = item;
          break;
        }
      }
      return marker;
    },
    checkboxChange(e) {
      const { name, value } = e;
      const marker = this.findMarkerById(name);
      const entityType = marker.getExtData().entityType;
      const sizes = entityType === "school" ? [40, 50] : [30, 40];
      const active = value ? "_active" : "";
      marker.setIcon(
        new AMap.Icon({
          image: `static/certificate/${entityType}_icon${active}.svg`,
          size: new AMap.Size(sizes[0], sizes[1]),
          imageSize: new AMap.Size(sizes[0], sizes[1])
        })
      );
    },
    handleEntityDelete(info) {
      const _this = this;
      const { id, name } = info;
      uni.showModal({
        title: "提示",
        content: `确定要删除 ${name} 吗？`,
        success: async function(res) {
          if (!res.confirm) return;
          const idx = _this.entityList.findIndex(item => item.id === id);
          _this.entityList.splice(idx, 1);
          const marker = _this.findMarkerById(id);
          marker && _this.clearMarker(marker);
        }
      });
    },
    handleOpenSwipe(idx) {
      this.entityList[idx].show = true;
      this.entityList.map((val, i) => {
        if (idx != i) this.entityList[i].show = false;
      });
    },
    // 新增实体
    addEntityTypeConfirm(info) {
      const typeFlag = info[0].value === "custom";
      const page = typeFlag ? "addCustomEntity" : "addCommonEntity";
      const params = {};
      params.curLocation = this.curCords;
      if (!typeFlag) {
        params.type = info[0].value;
      }
      this.$u.route({
        url: `pages/certificate/fieldAudit/orientationDiagram/${page}`,
        params
      });
    }
  }
};
</script>

<style lang="scss" scoped>
uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

.page {
  padding: 0;
}

#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}

.m-market {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #f2f4f5;
  .add-entity {
    position: absolute;
    top: -100rpx;
    left: 20rpx;
    display: flex;
    padding: 14rpx;
    background-color: #ffffff;
    border-radius: 6rpx;
    .add-text {
      color: #000000;
      font-size: 20rpx;
      font-weight: bold;
      line-height: 46rpx;
    }
  }
  .button {
    margin: 30rpx;
  }
  .entity-list {
    max-height: 420rpx;
    overflow-y: auto;
    .title-wrap {
      display: flex;
      justify-content: space-between;
      padding-left: 12rpx;
      .left {
        font-size: 26rpx;
        width: 454rpx;
        .name {
          color: #333333;
          font-weight: bold;
        }
        .address {
          color: #666666;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }
      .right {
        position: relative;
        width: 26%;
        display: flex;
        justify-content: center;
        .distance {
          color: #666666;
          font-size: 20rpx;
          font-weight: bold;
          position: absolute;
          .number {
            color: #fa3534;
            font-size: 22rpx;
            display: inline-block;
            margin: 0 4rpx;
          }
        }
      }
    }
  }
}
.swipe-root:not(.swipe-root:last-child) {
  margin-bottom: 10rpx;
}
/deep/.u-checkbox {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  width: 100%;
}
/deep/.u-checkbox__label {
  width: 100% !important;
  margin: 0 12rpx;
}
.u-size-default {
  font-size: 28rpx;
}
</style>
